<?php

namespace App\Http\Middleware;

use Closure;
use GuzzleHttp\ClientInterface;
use Illuminate\Container\Container;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Arr;

class SimpleSSOAuth
{
    protected $http;

    public function __construct(ClientInterface $client)
    {
        $this->http = $client;
    }

    /**
     * Handle an incoming request.
     * @throws \Exception
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!isset($_COOKIE['usertoken'])) {
            return $this->unauthorizedResponse('没有user-token');
        }

        $token = $_COOKIE['usertoken'];

        $config = Container::getInstance()->make('config');
        $api = $config->get('console.check_login_url') . '?' . http_build_query(['usertoken' => $token]);

        $response = $this->http->request('GET', $api);
        //var_dump($response);exit;
        if ($response->getStatusCode() !== 200) {
            throw new \Exception('Bad response from console server: ' . (string) $response->getBody());
        }

        $content = $response->getBody()->getContents();

        if (empty($content)) {
            throw new \Exception('Unauthorized');
        }

        $profile = json_decode($content, true);

        if ($code = Arr::get($profile, 'code') != 10000) {
            return $this->unauthorizedResponse($code);
        }

        return $next($request);
    }

    protected function unauthorizedResponse($traces = null)
    {
        return new JsonResponse([
            'code' => 401,
            //'message' => '请登录后使用未登录web.api',
            'message' => $traces,
            'traces' => $traces,
        ]);
    }
}
